import axios from 'axios'
import { useUserStore } from '../stores/user'

const request = axios.create({
    baseURL: 'http://106.55.44.124:9595',
    timeout: 10000,
    withCredentials: true
})

// 响应拦截器
request.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code === 0) {
            return res
        }
        // 未登录或会话过期
        if (res.code === 40100) {
            const userStore = useUserStore()
            userStore.clearUserState()
            window.location.href = '/login'
            return Promise.reject(new Error('请先登录'))
        }
        return Promise.reject(new Error(res.message || '未知错误'))
    },
    error => {
        console.error('请求错误:', error)
        return Promise.reject(error)
    }
)

export default request